package com.ruoyi.common.utils;

import com.ruoyi.common.utils.file.FileUtils;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VideoUtil {
    private static final Logger logger = LoggerFactory.getLogger(VideoUtil.class);

    public static void adjustVideoResolutions(String originalPath, String targetFilePath) {

        File folder = new File(originalPath);
        File[] listOfFiles = folder.listFiles();
        //目标文件没有创建文件夹
        File outputFile = new File(targetFilePath);
        File outputDir = outputFile.getAbsoluteFile();
        // 如果文件夹不存在，则创建文件夹
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
        if (listOfFiles == null) {
            logger.info("The directory is empty or it does not exist.");
            return;
        }
        String finalOutputPath = targetFilePath;
        ExecutorService executor = Executors.newFixedThreadPool(40);

        for (File file : listOfFiles) {
            CompletableFuture<Void> f1 = CompletableFuture.runAsync(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    if (file.isFile()) {
                        System.out.println("File: " + file.getAbsolutePath());
                        String savePath = finalOutputPath + "/" + FileUtils.getName(file.getAbsolutePath());

                        String inputPath = file.getAbsolutePath();
                        String ffmpegCommand = String.format(
                                "ffmpeg -i %s -vf scale=%d:%d %s",
                                inputPath, 390, 240, savePath
                        );

                        try {
                            Process process = Runtime.getRuntime().exec(ffmpegCommand);
                            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                            String line;
                            while ((line = reader.readLine()) != null) {
                                System.out.println(line);
                            }

                            int exitCode = process.waitFor();
                            if (exitCode == 0) {
                                logger.info("视频分辨率调整成功，输出文件：{}",savePath);
                            } else {
                                logger.info("视频分辨率调整失败，错误代码：{}",exitCode);
                            }
                        } catch (IOException | InterruptedException e) {
                            e.printStackTrace();
                        }

                    } else if (file.isDirectory()) {
                        System.out.println("Directory: " + file.getAbsolutePath());
                    }
                }

            }, executor);
        }
    }

    public static void allVideoResolutions(String originalPath, String targetFilePath) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(40);

        originalPath = URLDecoder.decode(originalPath, "utf-8");
        // 指定要遍历的根目录路径
        Path rootPath = Paths.get(originalPath);
        // 遍历根目录下的所有文件和文件夹

        Files.walk(rootPath)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .forEach(path -> {
                    CompletableFuture<Void> f1 = CompletableFuture.runAsync(new Runnable() {
                        @Override
                        public void run() {
                            File file = path.toFile();
                            if (file.isFile()) {
                                String localPath = targetFilePath + "\\本地" + path.getParent().toString().substring(targetFilePath.length());
                                File outputDir = new File(localPath);
                                // 如果文件夹不存在，则创建文件夹
                                if (!outputDir.exists()) {
                                    outputDir.mkdirs();
                                }
                                String savePath = localPath + "\\" + path.getFileName();
                                Path tarSavePath = Paths.get(savePath);
                                if (!Files.exists(tarSavePath)) {
                                    String inputPath = file.getAbsolutePath();
                                    String ffmpegCommand = String.format(
                                            "ffmpeg -i %s -vf scale=%d:%d:flags=lanczos %s",

                                            inputPath, 768, 768, savePath
                                    );
                                    try {
                                        Process process = Runtime.getRuntime().exec(ffmpegCommand);
                                        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                                        String line;
                                        while ((line = reader.readLine()) != null) {
                                            System.out.println(line);
                                        }

                                        int exitCode = process.waitFor();
                                        if (exitCode == 0) {
                                            logger.info("视频分辨率调整成功，输出文件：{}",savePath);
                                        } else {
                                            logger.info("视频分辨率调整失败，错误代码：{}",exitCode);
                                        }
                                    } catch (IOException | InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }


                            } else if (file.isDirectory()) {
                                logger.info("Directory：{}",file.getAbsolutePath());
                            }
                        }
                    }, executor);
                });
    }
    public static Boolean delAllVedio(String targetPath) throws Exception{
        List<String> imageTypeList = Lists.newArrayList();
        imageTypeList.add("mp4");
        imageTypeList.add("avi");
        imageTypeList.add("mkv");
        imageTypeList.add("mov");
        imageTypeList.add("flv");
        imageTypeList.add("wmv");

        // 指定要遍历的根目录路径
        Path rootPath = Paths.get(targetPath);
        Files.walk(rootPath)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .forEach(path -> {
                    File file = path.toFile();
                    String extension = FilenameUtils.getExtension(file.getName());

                    if (file.isFile() && imageTypeList.contains(extension.toLowerCase())) {
                        // 如果是图片文件，执行删除操作
                        logger.info("删除文件{}",file.getName());
                        file.delete();
                    }
                });
        logger.info("路径：{}删除完成",targetPath);
        return Boolean.TRUE;
    }
    public static void main(String[] args) throws Exception {
        String path = "D:\\material\\Materialflow\\tuopan2";
        delAllVedio(path);
    }
}